using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using GoogleGeocoder;
using System.Text; 

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
        totalMatchingTitle.Visible = IsPostBack;
        clickInstructions.Visible = IsPostBack; 
    }
    
    protected void startSearchButton_Click(object sender, EventArgs e)
    {
        clickInstructions.Visible = true; 
        
        Coordinate coordinate = Geocode.GetCoordinates(addressTextBox.Text);
        LocationsData data = GetLocationData(coordinate);

        // Set up the locations 
        searchResults.DataSource = data.Location;
        searchResults.DataBind();

        // Set result count
        totalResultCount.Text = data.Location.Rows.Count > 0 ? data.Location.Rows.Count.ToString() : "No Results Found.";  
       
        // Get the locations, in JSON format. 
        string jsonScript = GetJSONLocations(data);

        // Get the home location (where the user entered their address) in JSON format. 
        string homeSpatialInfo = GetJsonHomeSpatialInfo(coordinate, addressTextBox.Text);

        // Write the JSON objects to the client. 
        ClientScript.RegisterClientScriptBlock(GetType(), "homeSpatialInfo", homeSpatialInfo, true); 
        ClientScript.RegisterClientScriptBlock(GetType(), "jsonMapObjects", jsonScript, true);
    }

    /// <summary>
    /// Gets the store locations and the coordinate for the "from" area (the address the user entered). 
    /// </summary>
    /// <param name="coordinate">A coordinate.</param>
    /// <param name="data">A LocationsData dataset.</param>
    private LocationsData GetLocationData(Coordinate coordinate)
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["StoresDb"].ConnectionString);
        connection.Open();
        
        string SQL = "GetNearbyLocations";
        SqlCommand command = new SqlCommand(SQL, connection);
        command.Parameters.Add(new SqlParameter("@CenterLatitude", coordinate.Latitude));
        command.Parameters.Add(new SqlParameter("@CenterLongitude", coordinate.Longitude));
        command.Parameters.Add(new SqlParameter("@SearchDistance", distanceDropDown.SelectedValue));
        command.Parameters.Add(new SqlParameter("@EarthRadius", 3961));  // In Miles
        command.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter da = new SqlDataAdapter(command);
        LocationsData data = new LocationsData(); 
        da.Fill(data.Location);
        return data; 
    }

    /// <summary>
    /// Gets a json variable for the home address and latitude/longitude coordinates.
    /// </summary>
    /// <param name="coordinate">The coordinate.</param>
    /// <param name="fromAddress">The address that of where the map is going to be locaed "from".</param>
    /// <returns>A string representation of a JSON variable.</returns>
    protected string GetJsonHomeSpatialInfo(Coordinate coordinate, string fromAddress)
    {
        string top = "var homeSpatialInfo = {"; 
        string bottom = "};";
        string jsonVariable = String.Format("\"latitude\" : \"{0}\", \"longitude\" : \"{1}\", \"fromAddress\" : \"{2}\"", coordinate.Latitude, coordinate.Longitude, HttpUtility.UrlEncode(fromAddress));

        return String.Concat(top, jsonVariable, bottom, Environment.NewLine); 
    }

    /// <summary>
    /// Retursn a JSON object in the format of a string. 
    /// <remarks>
    /// It should return a string that resembles a JSON object array in this format: 
    /// <example>
    /// var ProximityLocations = {"locations": [
    ///            {"name": "testName", "address": "123 test addre", "urladdress": "123+test+addre", "longitude": "192.009", "latitude" : "65.235"},
    ///            {"name": "tesdsfsdftName", "address": "65 test addre", "urladdress": "123+test+addre", "longitude": "3342.009", "latitude" : "633.235"},
    ///            {"name": "te33333333", "address": "123 test addre", "urladdress": "123+test+addre", "longitude": "123492.009", "latitude" : "15.235"}
    ///           ]};
    /// </example>
    /// 
    /// If there are no locations, the JSON object will be empty. 
    /// </remarks>
    /// </summary>
    /// <param name="data">The LocationData dataset that has the locations in it.</param>
    /// <returns>A string representation of a JSON object.</returns>
    protected string GetJSONLocations(LocationsData data)
    {
        string firstLine = "var ProximityLocations = {\"locations\": ["; 
        string lastLine = "]};";

        string JSONObjectFormat = "\"name\": \"{0}\", \"address\": \"{1}\", \"urladdress\": \"{2}\", \"longitude\": \"{3}\", \"latitude\" : \"{4}\"";

        StringBuilder builder = new StringBuilder();
        builder.AppendLine(firstLine);

        string jsonLocation; 
        string locationAddress; 

        foreach (LocationsData.LocationRow row in data.Location)
        {
            locationAddress = String.Format("{0}, {1}, {2}, {3}", row.Address, row.City, row.State, row.Zip);
            jsonLocation = String.Concat("{", String.Format(JSONObjectFormat,
                HttpUtility.HtmlEncode(row.LocationName),
                HttpUtility.HtmlEncode(locationAddress),
                HttpUtility.UrlEncode(locationAddress),
                row.Longitude,
                row.Latitude),
                "}", Environment.NewLine);
            builder.AppendLine(jsonLocation);

            // Only add comma if it is not the last row. The last row does not have a comma. See example in method comments.
            if (data.Location.Rows.IndexOf(row) != data.Location.Rows.Count-1)
            {
                builder.Append(',');
            }
        }

        builder.AppendLine(lastLine);
        return builder.ToString(); 
    }

    /// <summary>
    /// A variable to count the number of iterations in the repeater. Used for displaying organized data.
    /// </summary>
    protected int _itemCount = 0; 

    protected void searchResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        // Add the number to the screen for organization.
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            _itemCount++; 
            Literal locationNumber =(Literal) e.Item.FindControl("locationNumber");
            locationNumber.Text = _itemCount.ToString(); 
        }
    }
}
